package com.ruoyi.framework.web.service;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.domain.model.WechatSession;
import com.ruoyi.common.utils.WechatUtils;
import com.ruoyi.system.domain.SysMiniprogram;
import com.ruoyi.system.domain.SysMiniprogramUser;
import com.ruoyi.system.service.ISysMiniprogramService;
import com.ruoyi.system.service.ISysMiniprogramUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashSet;
import java.util.Set;

/**
 * 小程序登录服务
 * 
 * @author ruoyi
 */
@Service
public class MiniprogramLoginService
{
    @Autowired
    private ISysMiniprogramService miniprogramService;

    @Autowired
    private ISysMiniprogramUserService miniprogramUserService;

    @Autowired
    private TokenService tokenService;

    /**
     * 小程序登录
     * 
     * @param appId 小程序AppId
     * @param code 登录凭证
     * @return 登录用户信息
     */
    public LoginUser miniprogramLogin(String appId, String code)
    {
        // 1. 获取小程序配置
        SysMiniprogram miniprogram = miniprogramService.selectSysMiniprogramByAppId(appId);
        if (miniprogram == null)
        {
            throw new RuntimeException("小程序配置不存在");
        }

        // 2. 调用微信API获取会话信息
        WechatSession session = WechatUtils.getWechatSession(appId, miniprogram.getAppSecret(), code);
        if (!WechatUtils.isValidSession(session))
        {
            throw new RuntimeException("微信登录失败：" + (session != null ? session.getErrmsg() : "未知错误"));
        }

        // 3. 查询或创建小程序用户
        SysMiniprogramUser miniprogramUser = miniprogramUserService.selectSysMiniprogramUserByOpenId(session.getOpenid(), miniprogram.getMiniprogramId());
        if (miniprogramUser == null)
        {
            // 创建新用户
            miniprogramUser = new SysMiniprogramUser();
            miniprogramUser.setMiniprogramId(miniprogram.getMiniprogramId());
            miniprogramUser.setOpenId(session.getOpenid());
            miniprogramUser.setUnionId(session.getUnionid());
            miniprogramUser.setStatus("0");
            miniprogramUserService.insertSysMiniprogramUser(miniprogramUser);
        }
        else
        {
            // 更新最后登录时间
            miniprogramUser.setLastLoginTime(new java.util.Date());
            miniprogramUserService.updateSysMiniprogramUser(miniprogramUser);
        }

        // 4. 创建SysUser对象（小程序用户）
        SysUser sysUser = new SysUser();
        sysUser.setUserId(miniprogramUser.getUserId());
        sysUser.setUserName("miniprogram_" + miniprogramUser.getUserId());
        sysUser.setNickName(miniprogramUser.getNickName() != null ? miniprogramUser.getNickName() : "小程序用户");
        sysUser.setAvatar(miniprogramUser.getAvatarUrl());
        sysUser.setSex(miniprogramUser.getSex());
        sysUser.setStatus("0"); // 正常状态
        sysUser.setDelFlag("0"); // 未删除
        
        // 5. 创建LoginUser对象
        Set<String> permissions = new HashSet<>();
        permissions.add("miniprogram:user"); // 小程序用户权限
        LoginUser loginUser = new LoginUser(miniprogramUser.getUserId(), null, sysUser, permissions);
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + 30 * 60 * 1000L); // 30分钟过期
        
        // 6. 创建Token
        String token = tokenService.createToken(loginUser);
        loginUser.setToken(token);
        
        return loginUser;
    }
}
